package music

import (
	"dustbe/database"
	"dustbe/util"
	"errors"
	"fmt"
	"net/http"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

func checkPrivilegeByPublisherId(c *gin.Context, publisherId int) error {
	session := sessions.Default(c)
	user := session.Get("user")
	if user != nil {
		opName := user.(string)
		// 检查是否和发布者是同一人
		dustUser, err := database.FindUserById(publisherId)
		publisherName := dustUser.Name
		if err != nil || opName != publisherName {
			return errors.New("权限不足")
		}
	} else {
		// 直接返回
		return errors.New("你还未登录！")
	}
	return nil
}


type AlphaTexConfig struct {
	Title string `json:"title"`
	SubTitle string `json:"subtitle"`
	Artist string `json:"artist"`
	Album string `json:"album"`
	Words string `json:"words"`
	Music string `json:"music"`
	Copyright string `json:"copyright"`
	Tempo string `json:"tempo"`
	Instrument string `json:"instrument"`
	Capo string `json:"capo"`
	Tuning string `json:"tuning"`
}

type PublishPackage struct {
	PublisherId int `json:"publisherId"`
	CreateTime int `json:"createTime"`
	AlphaTex string `json:"alphaTex"`
	ImgUrl string `json:"imgUrl"`
	Config AlphaTexConfig `json:"config"`
}

type ExportAlphaTex struct {
	PublisherId int `json:"publisherId"`
	StaffId int `json:"staffId"`
	AlphaTex string `json:"alphaTex"`
	ImgUrl string `json:"imgUrl"`
	Config AlphaTexConfig `json:"config"`
}

func PublishStaff(c *gin.Context) {
	ok := util.LimitIpInterval(c, 10)
	if !ok {
		c.JSON(http.StatusOK, gin.H{"code" : 4001, "data" : "发布过于频繁"})
		return
	}

	var publishPackage PublishPackage
	if c.ShouldBindJSON(&publishPackage) != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "请求体格式错误"})
		return
	}

	publisherId := publishPackage.PublisherId
	createTime := publishPackage.CreateTime
	alphaTex := publishPackage.AlphaTex
	config := publishPackage.Config
	imgUrl := publishPackage.ImgUrl

	err := checkPrivilegeByPublisherId(c, publisherId)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": err.Error()})
		return
	}

	dustUser, _ := database.FindUserById(publisherId)
	publisherName := dustUser.Name
	staffId, err := database.PublishStaff(publisherId, createTime, config.Title, imgUrl, publisherName)
	if err != nil {
		fmt.Println(err.Error())
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "数据库添加失败"})
		return
	}
	staffPath := fmt.Sprintf("%s/%d-%d.json", staffRoot, publisherId, staffId)
	
	exportAlphaTex := ExportAlphaTex{
		PublisherId: publisherId,
		StaffId: int(staffId),
		AlphaTex: alphaTex,
		Config: config,
		ImgUrl: imgUrl,
	}

	err = util.WriteJson(staffPath, exportAlphaTex)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "写入本地时出错"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code" : 200, "data" : "发布成功"})
}